/**
 * @modal: 订单商品明细
 */
import { Button, Descriptions, Form, Row, Col, Dropdown, Menu, Space, Table, Input, Popconfirm, Image, message } from 'antd';
import React, { useState, useEffect, useRef, useContext, useMemo } from 'react';
import { find } from 'lodash';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import GoodsSelectModal from '@/pages/OrderModule/common/bizcomponents/GoodsSelectModal';
import GoodsListModal from '@/pages/GoodsModule/combinationGoods/component/GoodsListModal'
import { NumText } from '@/pages/OrderModule/common/components/CommonText/components/NumText';
import Typography from '@/pages/OrderModule/common/components/Typography';
import ConfirmPayModal from '../../components/ConfirmPayModal';
import { formatSysImg, formatAmount, cpText } from '@/utils/utils';
import orderUtils from '@/pages/OrderModule/common/utils/order';
import { relieveMatch, singleUpdateOrderGoods, sureUpdateOrderGoods, setBatchPackageGiftOp, modifyGoodsAttributeOp } from '../../../../services';
import { searchOrderByIds, searchHistoryOrderByIds, searchAvailableNumsById } from '../../../OrderList/services';
import styles from './index.module.less';
import PackageAndGiveawayTabs from '@/pages/OrderModule/common/bizcomponents/PackageAndGiveawayTabs';
import { DownOutlined } from '@ant-design/icons'
import GoodsMatchDrawer from "@/pages/GoodsModule/systemGoods/components/Actions/GoodsMatchDrawer/index";
import EidtContent from './EidtContent';
import CommonLoading from '@/components/CommonLoading';
import { payMethMap, flag } from '@/utils/config.js';
import CommonTag from '@/components/CommonTag';
import IconFont from '@/components/IconFont';
import { getInfoGoodsSku } from '@/pages/GoodsModule/systemGoods/service.js';

const payStateMap = {
  0: '未支付', 
  1: '已支付',
  2: '部分支付'
}

const EmptyContent = () => {
  return <div style={{width:'100%', height:'100%', display:'flex', justifyContent:'center', alignItems:'center'}}>/</div>
}

const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  promiseFunc,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);
  const toggleEdit = (bool) => {
    if(bool){
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    }
  };

  const formatCount = (value) => {
    let goodsNum = parseInt(value) || 1;
    goodsNum = Math.max(1, goodsNum);
    goodsNum = Math.min(999999, goodsNum);
    return goodsNum;
  }

  //单元格保存提交
  const save = async () => {
    try {
      const values = await form.validateFields(), field = Object.keys(values)[0];
      toggleEdit(true);
      if(record[field] == values[field]) return;
      const combineObj =  { ...record, ...values},
       rowData = { ...combineObj, goodsNum: formatCount(combineObj.goodsNum) };
       const { orderId, id, sysGoodsId, skuCode: sysSkuCode, goodsNum, goodsName: sysGoodsName, } = rowData;
      if(rowData.orderGoodsType == 'goods'){//商品
        if(field == 'sysGoodsName'){//名称
          promiseFunc(1, {
            ...values,
            orderGoodsId: id
          })
        }else{//数量
          promiseFunc(2, {
            updateOrderGoodsList: [{
              goodsNum,
              id,
              sysGoodsName,
              sysGoodsId,
              sysSkuCode
            }]
          })
        }
      }else if(field == 'goodsNum'){
        promiseFunc(3, {
          orderAccessoryList: [{
            goodsNum,
            id
          }]
        })
      }
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={()=>toggleEdit(record.orderGoodsType == 'goods' || dataIndex == 'goodsNum')}
      >
        {children}
      </div>
    );
  }
  return <td {...restProps}>{childNode}</td>;
};

function OrderItemDetailModal({ isInit = true, records, handleSingleUpdate, actions, wrapperStyle = {}, ...args }) {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [amountObj, setAmountObj] = useState(null);
  const [modalStatus, setModal] = useState(false);
  const [matchInfo, setMatchInfo] = useState({});

  const stageParams = useRef({});

  const { runVolume, type: orderType, state: orderState, payState, payMeth, goodsList = [], accessoryList = [] } = records;

  useEffect(()=>{
    isInit && getOrderGoodsFunc();
  }, [isInit])

  const statisticsObj = useMemo(() => {
    let totalKind = 0, totalCount = 0, allCount = 0, totalAmount = 0, totalWeight = 0;
    data.map(item=>{
      const singleNum = Number(item.goodsNum)  || 1;
      if(item.orderGoodsType == 'goods'){
        totalKind += 1;
        totalCount += singleNum;
      }
      allCount += singleNum;
      totalAmount += (item.storeGoodsPrice * 1000) * singleNum;
      totalWeight += (item.weight || 0) * 10000 * singleNum;
    })
     return { totalKind, totalCount, allCount, totalAmount: totalAmount / 1000, totalWeight: totalWeight / 10000 };
  }, [data])

  const getOrderGoodsFunc = async () => {
    setLoading(true);
     let res;
     if(actions == "history") { //历史
        res = await searchHistoryOrderByIds({orderId: records.id});
     } else {
        res = await searchAvailableNumsById({id:records.id});
     }
    const { data: newData, success} = res;
    setLoading(false);
    if(success && newData){
      const arr = [];
      [newData].map(item=>{
        const { goodsList: orderGoodsVOList = [], accessoryList: orderAccessoryVOList = [] } = item;
        orderGoodsVOList.map(item=>{
          //库存字段
          arr.push({
            ...item,
            orderId: records.id,
            orderGoodsType: 'goods',
            storeGoodsPrice: Math.max(item.goodsPrice, 0),
          })
        })
        orderAccessoryVOList.map(item=>{
          arr.push({
            ...item,
            orderGoodsType: item.type == 1 ? 'gifts' : 'package',
            storeGoodsPrice: item.goodsPrice,
          })
        })
      })
      setData(orderUtils.sortGoodsByGoodsType(arr));
    }
  }

  const handleSave = (row) => {
    const newData = [...data];
    const index = newData.findIndex((item) => row.id === item.id);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setData(newData);
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  //解除匹配
  const handleRelieveMatch = async (obj, index) => {
    setLoading(true);
    const { success, msg } = await relieveMatch({
      orderIds: [records.id],
      cancelGoodsMatchList: [{
        supplierSkuId: obj.storeId,
        sysGoodsId: obj.sysGoodsId
      }]
    });
    setLoading(false);
    if(success){
      message.success(msg);
      getOrderGoodsFunc();
    }
  }

  //编辑商品
  const handleUpdateGoods = async (type, index, list = [], isCustom) => {
    const params = {
      orderId: records.id
    };
    if(type == 'add'){
      const filterList = [];
      list.map(item=>{
        const { id, num, skuName:sysGoodsName, skuCode: sysSkuCode } = item;
        const obj = find(data, ['sysGoodsId', id]);
        if(!obj){
          filterList.push({
            goodsNum: num || 1,
            id,
            sysGoodsId: id,
            sysGoodsName,
            sysSkuCode
          })
        }
      });
      if(filterList?.length != list?.length){
        message.info('存在相同的商品已跳过！');
        if(!filterList?.length) return
      }
      if(isCustom) { //自定义商品
        params.addOrderGoodsList = list;
      } else {
        params.addOrderGoodsList = filterList;
      }
    }else if(type == 'delete'){
      if(data[index].orderGoodsType == 'goods'){
        const list = data.filter(item=>item.orderGoodsType == 'goods');
        if(list?.length == 1){
          return message.info('该商品为最后一个商品，不能删除');
        }
      }
      params.delOrderGoodsId = [data[index].id];
    }else{//换
      const { id, num: goodsNum, skuName: sysGoodsName, skuCode: sysSkuCode } = list[0] || {};
      if(isCustom) { //自定义商品
        params.changeNewOrderGoodsList = list.map(item => {return {...item, originalId: data[index].id}})
      } else {
        params.changeNewOrderGoodsList = [{
            sysGoodsName,
            sysSkuCode,
            sysGoodsId: id,
            goodsNum: goodsNum || data[index].goodsNum,
            originalId: data[index].id,
          }];
      }
    }
    setLoading(true);
    const { data: res, success, msg } = await singleUpdateOrderGoods(params);
    setLoading(false);
    if(success && res){
      const { resultHandleType, payAmount, tradeNo } = res;
      stageParams.current = { ...params, tradeNo };
      if(resultHandleType == 1){
        handleSingleUpdate?.(records.id)
        message.success(msg);
        getOrderGoodsFunc();
      }else{
        setAmountObj(payAmount);
      }
    }
  }

  //单元格修改
  const promiseFunc = async (type, params) => {
    if(type == 1 || type == 2){
      params.orderId = records.id;
    }else{
      params.orderIds = [records.id];
    }
    setLoading(true);
    let request;
    if(type == 1){
      request = await modifyGoodsAttributeOp(params);
    }else if(type == 2){
      request = await singleUpdateOrderGoods(params);
    }else{
      params.setType = 5;
      request = await setBatchPackageGiftOp(params);
    }
    const { data: res, success, msg } = request;
    setLoading(false);
    if(success && res){
      if(type == 1 || type == 3){
        handleSingleUpdate?.(records.id)
        message.success(res?.msg || msg);
        getOrderGoodsFunc();
        return
      }
      const { resultHandleType, payAmount, tradeNo } = res;
      stageParams.current = { ...params, tradeNo };
      if(resultHandleType == 1){
        handleSingleUpdate?.(records.id)
        message.success(msg);
        getOrderGoodsFunc();
      }else{
        setAmountObj(payAmount);
      }
    }
  }

   //确定修改
   const handleSureModify = async (password) => {
    setLoading(true);
    const { msg, success} = await sureUpdateOrderGoods({
      password,
      ...stageParams.current,
      index: undefined,
      newData: undefined
    });
    setLoading(false);
    if(success){
      handleSingleUpdate?.(records.id)
      message.success(msg);
      getOrderGoodsFunc();
      setAmountObj(undefined);
    }
  }

  const [updateKey, setUpdateKey] = useState(0);

  //更新包材
  const handleUpdatePackage = async (type, index, list = []) => {
    const params = {
      orderIds: [records.id],
      orderAccessoryList: []
    }
    if(type == 'add'){
      params.addStrategy = 3;
      params.setType = 1;
      list.map(item=>{
        params.orderAccessoryList.push({
          ...item,
          type: item.orderGoodsType == 'package' ? 0 : 1,
          goodsNum: item.goodsNum || 1,
          spu: item.goodsCommonid,
          weight: item.goodsWeight
        })
      })
    }else if(type == 'delete'){
      params.setType = 2;
      params.orderAccessoryList.push({
        id: data[index]?.id
      })
    }else{
      params.setType = 5;
      params.orderAccessoryList.push({
        id: data[index]?.id
      })
    }
    const { msg, success, data: res } = await setBatchPackageGiftOp(params);
    if(success){
      handleSingleUpdate?.(records.id)
      message.success(res?.msg || msg);
      getOrderGoodsFunc();
      setModal(false);
      setUpdateKey(updateKey+1);
    }
  }

  //换商品渲染原商品
  const [currentRecord, setRecord] = useState({});

  const renderOldGoods = useMemo(()=>{
    const { buyerMessage, flag:flagArr, sellerMessage } = records;
    const { skuCode, goodsSpec, goodsName } = currentRecord;
     return (<>
     <Descriptions column={2}>
      <Descriptions.Item label="买家留言">{buyerMessage || '-'}</Descriptions.Item>
      <Descriptions.Item label="卖家备注">
         {(flagArr || []).map((v) => {
          return (
            <span key={v} style={{ fontSize: '20px', marginRight: '4px' }}>
              <IconFont type={flag[v]} />
            </span>
          );
		     })}
        {sellerMessage || '-'}
      </Descriptions.Item>
      <Descriptions.Item label="商品编码">{skuCode}</Descriptions.Item>
      <Descriptions.Item label="颜色规格">{goodsSpec}</Descriptions.Item>
      <Descriptions.Item label="商品名称">{goodsName}</Descriptions.Item>
    </Descriptions>
     </>)
  }, [currentRecord])

  //点击删除操作
  const handleClickDelete = (orderGoodsType, index) => {
    if(orderGoodsType == 'goods'){
      handleUpdateGoods('delete', index);
    }else{
      handleUpdatePackage('delete', index);
    }
  }

  //批量复制功能
  const handleClickBatchCopy = () => {
    const arr = [];
    data.map((item) => {
      arr.push(...(item.goodsUniqueCodeList || []));
    })
    cpText(arr?.filter(item=>item)?.join('\r\n'));
  }

  const goodsType = {
    '3': '手工添加',
    '4': '手工换货',
    '5': '售后换货',
    '6': '售后补发',
  }

  const defaultColumns = [
    {
      title: '商品',
      dataIndex: 'sysGoodsName',
      width: 262,
      render(value, el) {
        const textMap = {
          gifts: `【赠品】`,
          package: `【${runVolume ? '跑量' : ''}包装】`,
          goods: `${runVolume ? '【跑量商品】' : ''}`
          // runGifts: `【跑量赠品】`,
          // runPackage: `【跑量包装】`,
        }
        const { goodsImage, goodsName, goodsSpec, storeName, storeId, size, type, id, orderGoodsType, isSysComposeGoods, refundType, refundStatus, takeGoodsState, deliveryStatus } = el;
        return <div style={{display:'flex'}}>
          <Image src={formatSysImg(goodsImage, storeId)} style={{width: '64px', height: '64px', borderRadius:'6px'}}/>
          <div style={{flex: 1, marginLeft:'8px'}}>
          <div className='textOverflowMultiThree'>
            <span style={{color:'#0068FF'}}>【{storeName || '无供应商'}】</span>
            { (!runVolume && orderGoodsType == 'goods') ? <EidtContent textNode={goodsName} handleOk={(sysGoodsName)=>promiseFunc(1, {sysGoodsName, orderGoodsId: id})} />
            : <span>{goodsName}{textMap[el.orderGoodsType] || ''}</span>}
           </div>
           <div style={{display:'flex', justifyContent:'space-between'}}>
              <span style={{flex: 1, color: '#7C7E82'}}>{goodsSpec}</span>
              <span style={{color:'#00BC75'}}>{goodsType[type]}</span>
           </div>

           {!!isSysComposeGoods && <CommonTag type='zuhe' />}
           {refundStatus == 2 && <CommonTag type='tuikuansuccess' />}
           {refundStatus == 3 && <CommonTag type='tkgb' />}
           {refundType == 1 && refundStatus == 1 && <CommonTag type='jtkdcl' />}
           {refundType == 2 && refundStatus == 1 && <CommonTag type='thtkdcl' />}
           {deliveryStatus == 1 && <CommonTag type='otherPlatDelivery' />}
           <CommonTag type={`takeGoodsState${takeGoodsState}`} />
        </div>
     </div>
      },
    },
    {
      title: '商品编码',
      dataIndex: 'sysSkuCode',
      width: 82,
      render(text, record) {
        const value = text || record.goodsId;
        return <Typography 
          as="s1" 
          // onClick={()=>window.open(`${GOODS_HREF}${value}`)} 
          style={{cursor:'pointer'}}
        >
          {value}
        </Typography>;
      },
    },
    {
      title: '款式编码',
      dataIndex: 'sysSpuCode',
      width: 82,
      render(value, record) {
        return <Typography as="s1">{value || record.spu}</Typography>;
      },
    },
    {
      title: '档口号',
      dataIndex: 'storeCode',
      width: 70,
    },
    {
      title: '数量',
      dataIndex: 'goodsNum',
      width: 70,
      editable: true,
      render(value, { takeGoodsState, takeNum }) {
        return (<>
        <NumText as="s1" num={value} />
        { takeGoodsState == 5 && <div className="common-color10">(已拿{takeNum})</div>}
        </>);
      },
    },
    {
      title: '采购价',
      dataIndex: 'goodsPrice',
      width:82,
      render(value, { isVipGoods }) {
        return (<>
        {<div className='common-color9'>￥{value}</div>}
        {!!isVipGoods && <CommonTag type='isVipGoods' />}
        </>)
      },
    },
    {
      title: '金额',
      dataIndex: 'storeGoodsPrice',
      width: 80,
      render(value, { goodsNum }) {
        return (<>
        {!!value && <div>￥{value * goodsNum}</div>}
        </>)
      },
    },
    {
      title: '店铺价格',
      dataIndex: 'ecGoodsPrice',
      width:82,
      render(value, record, index) {
        const { orderGoodsType } = record;
        if(orderGoodsType == 'gifts' || orderGoodsType == 'package'){
          return <EmptyContent />;
        }
        return value ? <span>￥{value}</span> : '-';
      },
    },
    {
      title: '单品重量',
      dataIndex: 'weight',
      width:82,
      render(value) {
        return value ? <NumText as="s1" suffix="kg" num={value} /> : '0';
      },
    },
    {
      title: '可用库存',
      dataIndex: 'availableGoodsNum',
      width:82,
      render(value, record, index) {
        const { orderGoodsType } = record;
        if(orderGoodsType == 'gifts' || orderGoodsType == 'package'){
          return <EmptyContent />;
        }
        return value;
      },
    },
    {
      title: '支付状态',
      dataIndex: 'goodsPayState',
      width:82,
      render(value, { payMeth }) {
        return <>
        <Typography as="s1">{payStateMap[value]}</Typography>
        {Boolean(value) && <p>({payMethMap[payMeth]})</p>}
        </>;
      },
    },
    {
      title: (
        <div style={{ display: 'flex' }}>
          <span>唯一码</span>
          <div
            style={{ display: 'inline-block', marginLeft: '4px' }}
            onClick={() => handleClickBatchCopy('uniqueCode')}
          >
            <IconFont
              type="iconcopy"
              style={{ fontSize: '14px', cursor: 'pointer' }}
            />
          </div>
        </div>
      ),
      dataIndex: 'goodsUniqueCodeList',
      key: 'goodsUniqueCodeList',
      width: 100,
      render: text => {
        return (<>
         {
          text?.map(item=><p>{item}</p>)
         }
        </>)
      }
    },
    {
      title: '操作',
      dataIndex: 'field5',
      width: 100,
      fixed:'right',
      render(text, record, index) {
        const { orderGoodsType, isMatch, type, isCustom } = record;
        if(![10, 30].includes(orderState) || type == 2){
          return <EmptyContent />;
        }
        const spec = (orderState == 30 && payState && orderType == 1) || isCustom == 2;

        const renderMenu = () => {
          const handleClick = async (defaultTab) => {
             const { data, success } = await getInfoGoodsSku({ id: record.sysGoodsId});
            if (data && success) {
              setMatchInfo({
                defaultTab,
                data: [{
                  ...record,
                  availableInventory: record.availableGoodsNum,
                  ...(data || {}),
                  orderIds: [records.id]
                }]
              })
            }
          }
          if(isMatch){
            return <Menu>
            <Menu.Item >
              <Typography as="s1" onClick={()=>handleClick('精准匹配')}>更换匹配</Typography>
            </Menu.Item>
            <Menu.Item >
              <Popconfirm
                title="确认解除匹配吗?"
                onConfirm={() => handleRelieveMatch(record, index)}
              ><Typography as="s1">解除匹配</Typography>
              </Popconfirm>
            </Menu.Item>
          </Menu>
          }else{
           return <Menu>
            <Menu.Item>
              <Typography as="s1" onClick={()=>handleClick('精准匹配')}>匹配商品</Typography>
            </Menu.Item>
            <Menu.Item >
              <Typography as="s1" onClick={()=>handleClick('单个商品的智能匹配')}>智能匹配</Typography>
            </Menu.Item>
          </Menu>
          }
        }

         return (<span className="opera-span-common">
          {
            orderGoodsType == 'goods' && (<Dropdown overlay={renderMenu()} trigger='click' disabled={spec}>
            <Button size='small'>
              <Space>
                {`${isMatch == 1 ? '已' : '未'}匹配`}
                <DownOutlined />
              </Space>
            </Button>
          </Dropdown>)
          }

          {
            orderGoodsType == 'goods' && (orderState == 10 || orderState == 30) && (<GoodsSelectModal {...changeGoodsModalProps}>
              <Button type='link' onClick={()=>{stageParams.current.index = index; setRecord(record)}} style={{marginTop:'4px'}}>
                换商品
              </Button>
            </GoodsSelectModal>)
          }

          {
            (spec && orderGoodsType == 'package') ? (<Button type='link' disabled={true}>删除</Button>)
            : (<Popconfirm
            title="确认删除该商品吗?"
            onConfirm={() => handleClickDelete(orderGoodsType, index)}
          >
            <Button type='link'>删除</Button>
          </Popconfirm>)
          }

        </span>)
      },
    },
  ];

  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
        promiseFunc
      }),
    };
  });

  const confirmPayModalProps = {
    amountObj,
    handleOk: handleSureModify,
    handleCancel(){
     setAmountObj(null);
    },
  }

  //换商品
  const changeGoodsModalProps = {
    selectTitle: '换商品',
    node: renderOldGoods,
    selectName: 'change',
    isSingle: true,
    showCustomizeGoods: true,
    submitCallback(changedArr, isCustom){
      handleUpdateGoods('change', stageParams.current.index, changedArr, isCustom);
    },
    setSelectedRows(){
      return []
    },
    getInputNumberValues: (value) => { }
  }

  //商品匹配props
  const goodsMatchDrawerProps = {
    isSkuType: true,
    isOrderGoods: true,
    defaultTab: matchInfo.defaultTab,
    data: matchInfo.data,
    onCancel(ids){
      if(ids?.length){
        console.log(ids, records.id)
      }
      setTimeout(()=>{
        getOrderGoodsFunc();
        handleSingleUpdate?.(records.id);
      },500)
      setMatchInfo({});
    }
  }

  const modalProps = {
    showCustomizeGoods: true,
    handleCancel() {
      setModal(false);
    },
    onGoodsSkuListSelected(addArr, isCustom = false) {
      handleUpdateGoods('add', undefined, addArr, isCustom);
    },
    destroyOnClose: true,
};

  return (
    <div style={{...wrapperStyle}}>
      <Row gutter={[10, 10]}>
        {
          !runVolume && (<Col span={22}>
            <Space>
            {[10, 30].includes(orderState) && <Button size="small" onClick={()=>setModal('addGoods')}>添加商品</Button>}
            {
               [10, 30].includes(orderState) && !payState && (
                <Button size="small" onClick={()=>setModal('addPacking')}>添加包装或赠品</Button>
               )
            }
            </Space>
          </Col>)
        }
        <Col span={2}>
          <Typography as="s1">共{statisticsObj?.totalCount}件({statisticsObj?.totalKind}种)</Typography>
        </Col>
        <Col span={24}  className={styles.editTableCell}>

        <Table
          columns={columns}
          dataSource={data}
          components={components}
          pagination={false}
          bordered
          scroll={{ x: 1000, y: 500 }}
          rowKey='id'
          summary={pageData => {


            return (
              <Table.Summary fixed>
              <Table.Summary.Row >
                <Table.Summary.Cell>总计</Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell>{statisticsObj?.allCount}</Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell><span className='common-color9' style={{ fontWeight: 500 }}>￥{formatAmount(statisticsObj?.totalAmount)}</span></Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell>{statisticsObj?.totalWeight}kg</Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
              </Table.Summary.Row>
              </Table.Summary>
            );
          }}
        />
        </Col>
      </Row>
      {amountObj && <ConfirmPayModal {...confirmPayModalProps} />}
      <CommonModal
        title= '添加包装或赠品'
        visible={modalStatus == 'addPacking'}
        width = {800}
        onOk= {()=>{
          const addOrderGoodsList = [];
          stageParams.current.packageSource.map(item=>{
            addOrderGoodsList.push({
              goodsNum: item.goodsNum || 1,
              sysGoodsId: item.goodsId,
              sysGoodsName: item.goodsName,
              sysSkuCode: item.goodsId,
            })
          })
          handleUpdatePackage('add', undefined, stageParams.current.packageSource)
        //   const newArr = cloneDeep(data);
        //   stageParams.current.packageSource.map(item=>{
        //     const obj = find(newArr, ['goodsId', item.goodsId]);
        //     if(!obj){
        //       const { goodsCommonid, goodsId, goodsPrice  } = item;
        //      newArr.push({
        //       ...item,
        //       goodsNum: item.goodsNum || 1,
        //       type: item.orderGoodsType == 'package' ? 0 : 1,
        //       goodsCode: goodsId,
        //       amount: goodsPrice * 1000 * (item.goodsNum || 1) / 1000,
        //       isCustom: 0,
        //       isVipGoods: 0,
        //       outStoreSku: goodsId,
        //       outStoreSpu: goodsCommonid,
        //      });
        //     }
        //   })
        //  setData(orderUtils.sortGoodsByGoodsType(newArr));
        //  setModal(false);
        }}
        onCancel={()=>{setModal(false);setUpdateKey(updateKey+1)}}
        >
          {
            modalStatus == 'addPacking' &&  <div key={updateKey}>
            <PackageAndGiveawayTabs
              onSelectionChange={(list)=>stageParams.current.packageSource = list }
            />
          </div>
          }
      </CommonModal>
      <CommonLoading loading={loading} />
      { matchInfo.defaultTab && <GoodsMatchDrawer {...goodsMatchDrawerProps} />}
      { modalStatus == 'addGoods' && <GoodsListModal {...modalProps} />}
    </div>
  );
}

export default OrderItemDetailModal;
